<script lang="ts" setup>
import type { VbenFormSchema } from '#/adapter/form';

import { ref, watch } from 'vue';

import { IconifyIcon } from '@vben/icons';

import { Button, message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';

// Props
const props = defineProps<{
  fields: any[];
}>();

// 响应式数据
const submitting = ref(false);
const formData = ref({});

// 生成表单Schema
const generateFormSchema = (): VbenFormSchema[] => {
  return props.fields.map((field) => {
    const schema: VbenFormSchema = {
      fieldName: field.name,
      label: field.label,
      component: getComponentByType(field.type),
      componentProps: {
        placeholder: field.uiConfig?.placeholder || `请输入${field.label}`,
        ...field.uiConfig,
      },
      rules: generateFieldRules(field),
    };

    // 处理特殊组件类型
    if (field.type === 'SELECT' && field.options) {
      schema.componentProps.options = field.options;
    } else if (field.type === 'SELECT' && !field.options) {
      // 为SELECT类型提供默认选项
      schema.componentProps.options = [
        { label: '选项1', value: 'option1' },
        { label: '选项2', value: 'option2' },
        { label: '选项3', value: 'option3' },
      ];
    }

    return schema;
  });
};

// 根据字段类型获取组件
const getComponentByType = (type: string): string => {
  const typeMap: Record<string, string> = {
    STRING: 'Input',
    NUMBER: 'InputNumber',
    BOOLEAN: 'Switch',
    DATE: 'DatePicker',
    SELECT: 'Select',
    TEXTAREA: 'Textarea',
    UPLOAD: 'Upload',
  };
  return typeMap[type] || 'Input';
};

// 生成字段验证规则
const generateFieldRules = (field: any) => {
  const rules: any[] = [];
  rulesrules;

  // 必填验证
  if (field.required) {
    rules.push('required');
  }

  // 添加其他验证规则
  if (field.validation) {
    if (field.validation.min !== undefined) {
      rules.push({ min: field.validation.min });
    }
    if (field.validation.max !== undefined) {
      rules.push({ max: field.validation.max });
    }
    if (field.validation.pattern) {
      rules.push({ pattern: new RegExp(field.validation.pattern) });
    }
  }

  return rules;
};

// 使用useVbenForm
const [Form, formApi] = useVbenForm({
  layout: 'horizontal',
  schema: generateFormSchema(),
  showDefaultActions: false,
});

// 监听表单数据变化
const watchFormData = async () => {
  try {
    const data = await formApi.getValues();
    formData.value = data;
  } catch (error) {
    console.error('获取表单数据失败:', error);
  }
};

// 提交表单
const submitForm = async () => {
  submitting.value = true;
  try {
    const { valid } = await formApi.validate();
    if (!valid) {
      message.error('请检查表单填写是否正确');
      return;
    }

    const data = await formApi.getValues();
    message.success('表单提交成功！');
    console.log('表单数据:', data);
  } catch (error) {
    message.error(`表单提交失败: ${error.message}`);
  } finally {
    submitting.value = false;
  }
};

// 重置表单
const resetForm = async () => {
  try {
    await formApi.resetForm();
    formData.value = {};
    message.success('表单已重置');
  } catch (error) {
    message.error(`重置表单失败: ${error.message}`);
  }
};

// 监听字段变化，重新生成表单
watch(
  () => props.fields,
  () => {
    // 字段变化时，表单会自动重新生成
    // 延迟一下再获取数据，确保表单已更新
    setTimeout(watchFormData, 100);
  },
  { deep: true, immediate: true },
);

// 监听表单数据变化
watch(
  formData,
  () => {
    // 表单数据变化时的处理
  },
  { deep: true },
);
</script>

<template>
  <div class="form-preview">
    <div class="preview-header">
      <h3>表单预览</h3>
      <div class="preview-actions">
        <Button type="primary" @click="submitForm" :loading="submitting">
          <IconifyIcon icon="ant-design:check-outlined" />
          提交表单
        </Button>
        <Button @click="resetForm">
          <IconifyIcon icon="ant-design:reload-outlined" />
          重置表单
        </Button>
      </div>
    </div>

    <div class="preview-content">
      <div v-if="fields.length === 0" class="empty-state">
        <IconifyIcon icon="ant-design:form-outlined" class="empty-icon" />
        <p>暂无字段配置，请先在"属性结构"中添加字段</p>
      </div>
      <Form v-else />
    </div>

    <div
      v-if="formData && Object.keys(formData).length > 0"
      class="preview-data"
    >
      <h4>表单数据</h4>
      <pre>{{ JSON.stringify(formData, null, 2) }}</pre>
    </div>
  </div>
</template>

<style lang="less" scoped>
.form-preview {
  .preview-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;

    h3 {
      margin: 0;
      color: #262626;
    }

    .preview-actions {
      display: flex;
      gap: 8px;
    }
  }

  .preview-content {
    margin-bottom: 20px;
  }

  .empty-state {
    text-align: center;
    padding: 40px 20px;
    color: #8c8c8c;

    .empty-icon {
      font-size: 48px;
      margin-bottom: 16px;
      color: #d9d9d9;
    }

    p {
      margin: 0;
      font-size: 14px;
    }
  }

  .preview-data {
    border-top: 1px solid #f0f0f0;
    padding-top: 20px;

    h4 {
      margin: 0 0 12px 0;
      color: #262626;
      font-size: 14px;
    }

    pre {
      background-color: #f5f5f5;
      padding: 12px;
      border-radius: 4px;
      font-size: 12px;
      color: #595959;
      margin: 0;
      overflow-x: auto;
      max-height: 200px;
      overflow-y: auto;
    }
  }
}
</style>
